package com.cyl.manager.ums.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyl.manager.act.domain.entity.IntegralHistory;
import com.cyl.manager.act.domain.entity.MemberCoupon;
import com.cyl.manager.act.mapper.IntegralHistoryMapper;
import com.cyl.manager.act.mapper.MemberCouponMapper;
import com.cyl.manager.oms.domain.entity.Aftersale;
import com.cyl.manager.oms.domain.entity.Order;
import com.cyl.manager.oms.domain.form.OrderQueryQy;
import com.cyl.manager.oms.mapper.AftersaleMapper;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.entity.Feedback;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.domain.entity.MemberAddress;
import com.cyl.manager.ums.mapper.FeedbackMapper;
import com.cyl.manager.ums.mapper.MemberCartMapper;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.AesCryptoUtils;
import com.ruoyi.livesass.api.domain.LbsGksc;
import com.ruoyi.livesass.api.domain.LbsGkscDay;
import com.ruoyi.livesass.api.mapper.LbsGkscDayMapper;
import com.ruoyi.livesass.api.mapper.LbsGkscMapper;
import com.ruoyi.system.service.ISysDeptService;
import cn.hutool.core.date.DateUtil;

import io.swagger.annotations.ApiModelProperty;

/**
 * 会员信息Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class MemberTbService {
    @Autowired
    private MemberMapper memberMapper;
    @Value("${aes.key}")
    private String aesKey;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private MemberCartMapper memberCartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AftersaleMapper aftersaleMapper;

    @Autowired
    private ISysDeptService deptService;
    
    
    @Autowired
    private LbsGkscMapper lbsGkscMapper;
    @Autowired
    private LbsGkscDayMapper lbsGkscDayMapper;
    @Autowired
    private IntegralHistoryMapper integralHistoryMapper;
    @Autowired
    private MemberCouponMapper memberCouponMapper;
    @Autowired
    private FeedbackMapper feedbackMapper;
    
    /**
     * 查询会员信息
     *
     * @param id 会员信息主键
     * @return 会员信息
     */
    public Member selectById(Long id) {
        return memberMapper.selectById(id);
    }
    
 
     
    /**
     * 	修改会员角色
     * @param memberId
     * @param rolezd
     * @param localDateTime 
     * @return
     */
    @Transactional
    public int xghyjs(Long memberId,Integer rolezd,Long spreaduid) {
    	String memberKey = Constants.MEMBER_INFO+"_"+memberId;
        redisCache.deleteObject(memberKey);
        
        Member memberdb = selectById(memberId);
        if(memberdb==null) {
	         throw new RuntimeException("会员id："+memberId+"不存在");
		}
        if(rolezd==null) {
	         throw new RuntimeException("角色不能为空");
        }
		if(rolezd.intValue() == 2) {
		 	QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
	        queryWrapper.eq("dept_dp_id", memberdb.getDeptDpId());
	        queryWrapper.eq("rolezd",rolezd);
	        int dzsl =  memberMapper.selectCount(queryWrapper);
	        if(dzsl>0) {
	        	throw new RuntimeException("只能设置一个店长");
	        }
		}
		
		if(memberdb.getRolezd().intValue() != 0) {//不是普通会员 
			if(rolezd.intValue() == 0 || rolezd.intValue() == -1 || rolezd.intValue() == 1) {
				QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
		        queryWrapper.eq("spreaduid",memberdb.getSpreaduid());
		        int hysl =  memberMapper.selectCount(queryWrapper);
		        if(hysl > 1) {
			        throw new RuntimeException("已经绑定有"+(hysl-1)+"个群会员，不能降级此会员");
				}
				
		 	}
		}
		if(rolezd.intValue() == 2 || rolezd.intValue() == 3  || rolezd.intValue() == 4) {//是 店长、副店长、店员
			
			List<Long> memberIds = new ArrayList<Long>();
			memberIds.add(memberId);
			Long deptZbjId = memberdb.getDeptZbjId();
			Long deptTzId  = memberdb.getDeptTzId();
			Long deptDpId  = memberdb.getDeptDpId();
			
			orderQy(memberIds, deptZbjId, deptTzId, deptDpId, memberId, LocalDateTime.now());

			UpdateWrapper<Member> updateWrapper = new UpdateWrapper<>();
	        updateWrapper
	        		.set("rolezd",rolezd)
	        		.set("spreaduid",memberId)
	                .set("update_time",LocalDateTime.now())
	                .eq("id",memberId);
	        return memberMapper.update(null,updateWrapper);
		}else {
			if(spreaduid.longValue() == memberId.longValue()) {
	        	throw new RuntimeException("设置后会员id:"+spreaduid+"角色不是店长、副店长、店员");
			}
		}
		
        Member memberdb2 = selectById(spreaduid);
        if(memberdb2==null) {
	         throw new RuntimeException("会员id："+spreaduid+"不存在");
		}
        Integer sprolezd = memberdb2.getRolezd();
		if(!(sprolezd.intValue() == 2 || sprolezd.intValue() == 3  || sprolezd.intValue() == 4)) {//不是店长、副店长、店员
        	throw new RuntimeException("会员id:"+spreaduid+"角色不是店长、副店长、店员");
		}
        
        if(memberdb2.getDeptDpId().intValue() != memberdb.getDeptDpId().intValue()) {
	         throw new RuntimeException("设置会员角色不能跨店铺！");
        }
        
        List<Long> memberIds = new ArrayList<Long>();
		memberIds.add(memberId);
		Long deptZbjId = memberdb2.getDeptZbjId();
		Long deptTzId  = memberdb2.getDeptTzId();
		Long deptDpId  = memberdb2.getDeptDpId();
		orderQy(memberIds, deptZbjId, deptTzId, deptDpId, spreaduid, LocalDateTime.now());

		UpdateWrapper<Member> updateWrapper = new UpdateWrapper<>();
        updateWrapper
        		.set("rolezd",rolezd)
        		.set("spreaduid",spreaduid)
                .set("update_time",LocalDateTime.now())
                .eq("id",memberId);
        return memberMapper.update(null,updateWrapper);
		 
		
        
    }
    /**
     * 	将会员批量迁移到另外一个 店长 副店长 店员
     * @param memberIds  要迁移的会员列表
     * @param newMemberId  新的 店长 副店长 店员id
     * @return
     */
    @Transactional
    public Map<String, Object> plqy(List<Long> memberIds,Long newMemberId) {
    	LocalDateTime localDateTime = LocalDateTime.now();
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<String> retmgs = new ArrayList<String>();
		int msgNum = 0;
		Member newMember = selectById(newMemberId);
		if(newMember==null) {
	         throw new RuntimeException("会员id："+newMemberId+"不存在");
		}
		Integer rolezd = newMember.getRolezd();
		if(rolezd == null) {
	        throw new RuntimeException("新会员角色不能为空");
		}
		if(rolezd.intValue() == -1) {
	        throw new RuntimeException("新会员角色不能为绑定店铺");
		}
		if(rolezd.intValue() == 0) {
	        throw new RuntimeException("新会员角色不能为普通用户");
		}
		if(rolezd.intValue() == 1) {
	        throw new RuntimeException("新会员角色不能为核销员");
		}
		Long deptZbjId = newMember.getDeptZbjId();
		Long deptTzId =  newMember.getDeptTzId();
		Long deptDpId =  newMember.getDeptDpId();
		QueryWrapper<Member> qw = new QueryWrapper<>();
		qw.in("id", memberIds);
		List<Member> list =  memberMapper.selectList(qw);
		if(list!=null) {
			List<Long> mids = new ArrayList<Long>();
			for (Member member : list) {
				mids.add(member.getId());
				msgNum = msgNum+1;
			}
			orderQy(mids, deptZbjId, deptTzId, deptDpId, newMemberId, localDateTime);
		}

		retMap.put("cg", "迁移成功"+msgNum+"个会员");
		retMap.put("sb", "迁移失败"+retmgs.size()+"个会员");
		retMap.put("sbyy", retmgs);
		return retMap;
    }
    //把群主和群主下的所以会员迁移到兴店铺（群主整体迁移）
    /**
     * 
     * @param qzMemberId 群主id
     * @param deptDpId  新店铺id
     * @return
     */
    @Transactional
    public Map<String, Object> qzztqy(Long qzMemberId,Long deptDpId) {
		LocalDateTime localDateTime = LocalDateTime.now();
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<String> retmgs = new ArrayList<String>();
		int msgNum = 0;
    	SysDept sysDept = deptService.selectDeptById(deptDpId);
		if(sysDept == null || sysDept.getBmlx()==null || !"5".equals(sysDept.getBmlx())) {
	           throw new RuntimeException("你选择的店铺不存在");
		}
		String ancestors = sysDept.getAncestors();
		if(ancestors!=null && ancestors.split(",").length == 4) {
	  		String[] as = sysDept.getAncestors().split(",");
    		Long deptZbjId = Long.parseLong(as[2]);
    		Long deptTzId = Long.parseLong(as[3]);
    		 QueryWrapper<Member> qw = new QueryWrapper<>();
    		 qw.eq("spreaduid", qzMemberId);
    		List<Member> list =  memberMapper.selectList(qw);
    		if(list!=null) {
    			List<Long> memberIds = new ArrayList<Long>();
    			for (Member member : list) {
    				memberIds.add(member.getId());
    				msgNum = msgNum+1;
    			}
    			orderQy(memberIds, deptZbjId, deptTzId, deptDpId, qzMemberId, localDateTime);
    			
    		}
		}
		retMap.put("cg", "迁移成功"+msgNum+"个会员");
		retMap.put("sb", "迁移失败"+retmgs.size()+"个会员");
		retMap.put("sbyy", retmgs);
		return retMap;
    }
    
    /**
     * 	订单迁移  人员，订单，售后，时长，时长天，积分，福利券，反馈
     * @param memberIds
     * @param deptZbjId
     * @param deptTzId
     * @param deptDpId
     * @param qzMemberId
     * @param localDateTime
     */
    private void orderQy(List<Long> memberIds,Long deptZbjId,Long deptTzId,Long deptDpId,Long spreaduid,LocalDateTime localDateTime) {
    	if(memberIds==null || memberIds.size()==0 ) {
    		return;
    	}
        SysDept sysDept = deptService.getCacheSysDept(deptDpId);
        if(sysDept==null || sysDept.getAddress() == null) {
	        throw new RuntimeException("店铺或店铺地址不能为空！");
        }
        
    	for (Long memberId : memberIds) {
    		String memberKey = Constants.MEMBER_INFO+"_"+memberId;
            redisCache.deleteObject(memberKey);
		}
    	//人员
    	UpdateWrapper<Member> updateWrapperMember = new UpdateWrapper<>();
		updateWrapperMember
        		.set("dept_dp_id",deptDpId)
        		.set("dept_tz_id",deptTzId)
        		.set("dept_zbj_id",deptZbjId)
                .set("spreaduid",spreaduid)
                .set("update_time",localDateTime)
                .in("id",memberIds);//人员迁移
        memberMapper.update(null,updateWrapperMember);

   
        //订单
		OrderQueryQy orderQueryQy = new OrderQueryQy();
		orderQueryQy.setDeptZbjId(deptZbjId);
		orderQueryQy.setDeptTzId(deptTzId);
		orderQueryQy.setDeptDpId(deptDpId);
		orderQueryQy.setSpreaduid(spreaduid);
		orderQueryQy.setUpdateTime(localDateTime);
		orderQueryQy.setUpdateTimeStr(DateUtil.format(localDateTime, "yyyy-MM-dd HH:mm:ss"));
		orderQueryQy.setMemberIds(memberIds);
		orderQueryQy.setReceiverName(sysDept.getLeader());
		orderQueryQy.setReceiverPhone(sysDept.getPhone());
		orderQueryQy.setReceiverPhoneEncrypted(AesCryptoUtils.encrypt(aesKey, sysDept.getPhone()));
		orderQueryQy.setReceiverProvince(sysDept.getProvince());
		orderQueryQy.setReceiverCity(sysDept.getCity());
        orderQueryQy.setReceiverDistrict(sysDept.getDistrict());
        orderQueryQy.setReceiverDetailAddress(sysDept.getAddress());
	        
		orderMapper.orderZd(orderQueryQy);//订单迁移
		

		UpdateWrapper<Aftersale> updateWrapperAftersale = new UpdateWrapper<Aftersale>();
		updateWrapperAftersale
		.set("dept_dp_id",deptDpId)
		.set("dept_tz_id",deptTzId)
		.set("dept_zbj_id",deptZbjId)
        .set("spreaduid",spreaduid)
        .set("update_time",localDateTime)
        .in("member_id",memberIds);//售后迁移
		aftersaleMapper.update(null,updateWrapperAftersale);
		
		
		
		UpdateWrapper<LbsGksc> updateWrapperLbsGksc = new UpdateWrapper<LbsGksc>();
		updateWrapperLbsGksc
		.set("dept_dp_id",deptDpId)
		.set("dept_tz_id",deptTzId)
		.set("dept_zbj_id",deptZbjId)
        .set("spreaduid",spreaduid)
        .set("update_time",localDateTime)
        .in("wc_user_id",memberIds);
		lbsGkscMapper.update(null,updateWrapperLbsGksc);//时长
		
		
		UpdateWrapper<LbsGkscDay> updateWrapperLbsGkscDay = new UpdateWrapper<LbsGkscDay>();
		updateWrapperLbsGkscDay
		.set("dept_dp_id",deptDpId)
		.set("dept_tz_id",deptTzId)
		.set("dept_zbj_id",deptZbjId)
		.set("dept_dp_name",sysDept.getDeptName())
        .set("spreaduid",spreaduid)
        .set("update_time",localDateTime)
        .in("wc_user_id",memberIds);//时长天
		lbsGkscDayMapper.update(null,updateWrapperLbsGkscDay);
		
		
		UpdateWrapper<IntegralHistory> updateWrapperIntegralHistory = new UpdateWrapper<IntegralHistory>();
		updateWrapperIntegralHistory
		.set("dept_dp_id",deptDpId)
		.set("dept_tz_id",deptTzId)
		.set("dept_zbj_id",deptZbjId)
        .set("spreaduid",spreaduid)
        .in("member_id",memberIds);//积分
		integralHistoryMapper.update(null,updateWrapperIntegralHistory);
		
		UpdateWrapper<MemberCoupon> updateWrapperMemberCoupon = new UpdateWrapper<MemberCoupon>();
		updateWrapperMemberCoupon
		.set("dept_dp_id",deptDpId)
		.set("dept_tz_id",deptTzId)
		.set("dept_zbj_id",deptZbjId)
        .set("spreaduid",spreaduid)
        .in("member_id",memberIds);//福利券
		memberCouponMapper.update(null,updateWrapperMemberCoupon);
	  
	   
		UpdateWrapper<Feedback> updateWrapperFeedback = new UpdateWrapper<Feedback>();
		updateWrapperFeedback
		.set("dept_dp_id",deptDpId)
		.set("dept_tz_id",deptTzId)
		.set("dept_zbj_id",deptZbjId)
        .set("spreaduid",spreaduid)
        .in("member_id",memberIds);//反馈
		feedbackMapper.update(null,updateWrapperFeedback);
		
	     
    }
    
	
}
